package com.aaa.threadsafety;

import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author C-Q
 * @version 1.1.0
 * @Description: 手动锁
 * Lock
 *实现类
 * @see-ReentrantLock--互斥锁：它的作用和synchronized类似
 * @see-Condition--条件锁（少用）
 * @see-ReadWriteLock--读写锁：当进行的为读操作不会上锁，写操作时进行上锁
 * @date 2022/11/1
 */
public class LockDemo {
    private static String [] arr=new String[2];
    private static int index=0;
    private static Object lock=new Object();
    public static void main(String[] args) throws InterruptedException {
        //创建手动锁对象
        Lock lock = new ReentrantLock();
        //构造函数中可以为线程提供任务对象Runnable
        //匿名实现类
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                    try {
                        //加锁
                        lock.lock();
                        if (arr[index] == null) {
                            arr[index] = "hello";
                            index++;
                        }
                    }finally {
                        //释放锁，要写在finally中一定会执行
                        lock.unlock();
                    }
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //加锁
                    lock.lock();
                    if (arr[index] == null) {
                        arr[index] = "world";
                        index++;
                    }
                }finally {
                    //释放锁，要写在finally中一定会执行
                    lock.unlock();
                }
            }
        });

        thread1.start();
//        thread1.setPriority(1);
//        thread2.setPriority(10);
        thread2.start();
        //不能直接打印，因为main线程可能先执行；
        thread1.join();
        thread2.join();
        System.out.println(Arrays.toString(arr));
    }
}
